﻿using AutoMapper;
using ManaMaple.Auth.Interface;
using ManaMaple.DB.Attributes;
using ManaMaple.DB.Models;
using ManaMaple.Entity.Sys;
using ManaMaple.IRepository.Sys;
using ManaMaple.IService.Sys;
using ManaMaple.Kit.Helpers;
using ManaMaple.Kit.Models;
using ManaMaple.Models.User.Request;
using ManaMaple.Models.User.VM;
using ManaMaple.Repository.Sys;
using ManaMaple.Service.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ManaMaple.Service.Sys
{
    /// <summary>
    /// 用户信息服务
    /// </summary>
    public class SysUsersService : FoundService<sys_user>,ISysUsersService
    {
        #region 构造
        public readonly ISysUsersRepository _sysUsersRepository;
        private readonly IMapper _mapper;
        public SysUsersService(IMapper mapper,IAuth _auth, ISysUsersRepository sysUsersRepository) : base(_auth)
        {
            _sysUsersRepository = sysUsersRepository;
            _mapper = mapper;
        }
        #endregion

        /// <summary>
        /// 使用用户名称查询用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<OperateResult> GetUserByName(string name)
        {
            var select = _sysUsersRepository.Select.Where(t => t.LoginName.Trim() == name);
            select = select.Where(t => t.IsDel == 0);
            var info = await select.FirstAsync();
            return OperateResult.SuccessOperate(info);
        }
        public Task Delete(sys_user sys_Users)
        {
            throw new NotImplementedException();
        }

        public async Task<OperateResult> GetList()
        {
            var list = await _sysUsersRepository.GetListAsync();
            return OperateResult.SuccessOperate(list);
        }
        [Transaction]
        public async Task Save(sys_user sys_Users)
        {
            var ss =  await _sysUsersRepository.InsertOrUpdateAsync(sys_Users);
            throw new Exception("1111");
        }

        public Task Update(sys_user sys_Users)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="sys_Users"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<OperateResult> UserLogin(sys_user sys_Users)
        {
            var bo = await _sysUsersRepository.UpdUserLasLoginTime(sys_Users.Id);
            if (!bo)
                return OperateResult.FailedOperate("更新失败");
            return OperateResult.SuccessOperate("");
        }

        #region 用户管理  
        /// <summary>
        /// 查询列表数据
        /// </summary>
        /// <returns></returns>
        public async Task<OperateResult> QuerytPageList(QueryUserRequest query)
        {
            var select = _sysUsersRepository.Select;
            #region 查询条件
            if (!string.IsNullOrWhiteSpace(query.UserName))
                select.Where(t => t.LoginName.Trim().Contains(query.UserName) || t.Name.Trim().Contains(query.UserName));
            if (query.IsEnable != null)
                select.Where(t => t.IsEnable == query.IsEnable);
            #endregion
            select = select.Where(t => t.IsDel == 0);
            var data = await _sysUsersRepository.GetPageListAsync(select, query);
            var dataM = _mapper.Map<PageReturn<SysUserVM>>(data);
            return OperateResult.SuccessOperate(dataM);
        }



        /// <summary>
        /// 用户保存
        /// </summary>
        /// <returns></returns>
        public async Task<OperateResult> SaveUser(SysUserVM vm)
        {
            if (vm == null)
                return OperateResult.FailedOperate("保存数据异常，请检查！");
            var sysUser = _mapper.Map<sys_user>(vm);
            GetConnUpdataUserInfo(sysUser);

            if (sysUser.Id == CurrenUserInfo.UserID && (sysUser.IsEnable == 0 || sysUser.IsDel == 1))
                return OperateResult.FailedOperate("当前登陆用户不能删除和禁用");
            //密码加密
            sysUser.Password = EncryptHelper.EncryptByMD5(sysUser.Password);
            var newUser = await _sysUsersRepository.InsertOrUpdateAsync(sysUser);
            if (newUser !=null )
                return OperateResult.SuccessOperate();
            else
                return OperateResult.FailedOperate("保存失败！");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        public async Task<OperateResult> DelUser(OperateUserRequest dto)
        {
            if (dto.Id <= 0)
                return OperateResult.FailedOperate("用户不存在，请检查！");
            var bo = await _sysUsersRepository.FalseDelete(dto.Id);
            if (bo)
                return OperateResult.SuccessOperate();
            else
                return OperateResult.FailedOperate("删除失败,请检查用户是否存在！");
        }

        /// <summary>
        /// 用户禁用或启用
        /// </summary>
        /// <returns></returns>
        public async Task<OperateResult> EnableUser(OperateUserRequest dto)
        {
            if (dto.Id <= 0)
                return OperateResult.FailedOperate("用户不存在，请检查！");
            var bo = await _sysUsersRepository.EnableUser(dto);
            if (bo)
                return OperateResult.SuccessOperate();
            else
                return OperateResult.FailedOperate("禁用/启用失败,请检查用户是否存在");
        }
        #endregion
    }
}
